import { codeValueList } from '@/api/common';

const getDefaultState = () => {
    return {
        token: localStorage.getItem('token') || '',
        uniqueId: '',
        name: '',
        avatar: '',
        roles: [],
        recommendCode: '',
        loginInfo: {},
        codeValue: ''
    };
};

const state = getDefaultState();

const mutations = {
    // 设置token
    setToken: (state, token) => {
        localStorage.setItem('token', token);
        state.token = token;
    },
    // 设置角色
    setRoles: (state, roles) => {
        state.roles = roles;
    },
    // 退出登录
    signOut: (state, path) => {
        let loginOrigin = process.env.VUE_APP_LOGIN_APP_ORIGIN;

        if (path) {
            // 登录成功后需要跳转回来
            let redirect = window.location.pathname;
            let hash = window.location.hash;
            hash = hash.replace('#/', '');
            loginOrigin = `${loginOrigin}?redirect=${redirect}&hash=${hash}`;
        }
        // 重置参数
        Object.assign(state, getDefaultState());
        localStorage.removeItem('token');
        window.location.href = loginOrigin;
    }
};

const actions = {
    // 获取接口code值
    getCodeValue({ commit, state }) {
        codeValueList().then(res => {
            state.codeValue = res.data;
        });
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
